package com.itheima.web.manager;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component //spring
public class AdminManager {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Reference
    AdminService adminService;

    public LineCaptcha getVerification(String uuid) {
        //1.调用工具类生成验证码图片
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(300, 150);

        //2.获取图片中的验证码
        String code = lineCaptcha.getCode();

        //3.将验证码放入redis中(5分钟)
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_CODE+uuid,code, Duration.ofMinutes(5));

        //4.返回图片
        return lineCaptcha;
    }

    public ResponseEntity login(String username, String password, String verificationCode, String uuid) {
        //1.判断验证码是否正确
        String redisCode = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_CODE + uuid);
        if (!StrUtil.equals(redisCode,verificationCode)) {
            throw new BusinessException("验证码错误");
        }

        //2.调用service通过用户查找用户
        Admin admin = adminService.findByUsername(username);

        //3.判断用户是否找到
        if (admin == null) {
            throw new BusinessException("用户不存在");
        }

        //4.判断密码是否正确
        if (!StrUtil.equals(admin.getPassword(), SecureUtil.md5(password))) {
            throw new BusinessException("密码错误");
        }

        //5.删除redis中的验证码
        stringRedisTemplate.delete(ConstantUtil.ADMIN_CODE + uuid);

        //6.生成token
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",admin.getId());
        claims.put("username",admin.getUsername());

        String token = JwtUtil.createToken(claims);

        //7.将token作为key,用户作为value放入redis中(可不做),设置失效时间1小时
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN+token, JSON.toJSONString(admin),Duration.ofHours(1));

        //8.将token放入map返回
        Map<String,String> map = new HashMap<>();
        map.put("token",token);
        return ResponseEntity.ok(map);
    }

    /*public ResponseEntity findAdminInfo(String token) {
        //1.处理token,前端工程师喜欢在token前面加"Bearer "
        if (StrUtil.isBlank(token)) {
            return ResponseEntity.status(401).body(null);
        }
        token = token.replace("Bearer ","");

        //2.从redis中获取用户信息
        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_TOKEN + token);

        //3.判断用户是否存在
        if (StrUtil.isBlank(json)) {
            return ResponseEntity.status(401).body(null);
        }

        Admin admin = null;
        try {
            admin = JSON.parseObject(json, Admin.class);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(401).body(null);
        }

        //4.token续期
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN+token,json,Duration.ofHours(1));

        //5.返回数据
        return ResponseEntity.ok(admin);
    }*/

    public ResponseEntity logout(String token) {
        //1.处理token,前端工程师喜欢在token前面加"Bearer "
        if (StrUtil.isBlank(token)) {
            return ResponseEntity.status(401).body(null);
        }
        token = token.replace("Bearer ","");

        //2.从redis中删除此token
        stringRedisTemplate.delete(ConstantUtil.ADMIN_TOKEN+token);

        return ResponseEntity.ok(null);
    }
}
